  //1.判断是否登录
  dl()
  function dl(){
    var tel = localStorage.getItem('tel')
  var denglu = $('.header .center .left ul .denglu')
  var zhuce = $('.header .center .left ul .zhuce')
  var tel = localStorage.getItem('tel')
      if(!tel){
          layer.msg('请先登录',{
              icon:2,
              time:1000
          },()=>{ 
              localStorage.setItem('url',location.href)
              location.href = './login.html'
          })
      }
  var str1 = ''
  var str2 = ''
  if(!tel){
    str1 += `
    <a href="./regeister.html">免费注册</a>
    `
    str2+=`
    <a href="./login.html">登录</a>
    `
    denglu.html(str2)
    zhuce.html(str1)
  }else{
    str1+=`
    <span style="color:yellow">
    欢迎用户${tel}回来
    </span>
    `
    str2+=`
    <a onclick='fn()'>退出</a>
    `
    denglu.html(str1)
    zhuce.html(str2)
  }
  }
  function fn(){
    layer.confirm('您确定要退出码？',{
                btn:['确定','取消']
            },()=>{
              layer.msg('退出成功，请重新登录',{
        icon:1,
        time:1000
      })
            })
    localStorage.removeItem('tel')
    dl()
  }
    var arr = localStorage.getItem('data')
      //2.经过判断是否获取到 - 没有数据就显示空空如也 - 有数据就继续
      arr = JSON.parse(arr)
      $.ajax({
      url: "https://list.mogu.com/search",
      method: "get",
      dataType: "jsonp",
      data: {
        callback: "jQuery21106216481125759377_1635845448722",
        _version: 8193,
        ratio: "3:4",
        cKey: 15,
        page: 1,
        sort: "pop",
        ad: 0,
        action: "boyfriend",
        acm: "3.mce.1_10_1ko5c.132244.0.rQ9uSsNB6z4ey.pos_879-m_482180-sd_119",
        ptp: "31.v5mL0b._head.0.YZ9U1BZE",
        _: 1635845448723,
      },
      success: (res) => {
        // console.log(res);
        var data = res.result.wall.docs;
        if(!arr){
          var str = `
            <div>
              <h1>购物车空空如也<h1>
                <p>赶紧去列表页挑选喜欢的商品吧！</p>
                <p><a class="btn btn-primary btn-lg" href="list.html" role="button">go to list</a></p>
            </div>
          `
          $('.container').html(str)
        }
        // arr = JSON.parse(arr)
        //从data中将存储起来数据筛选出来
        data = data.filter(item=>{   
            for(var i=0;i<arr.length;i++){
                if(arr[i].id === item.tradeItemId){
                    return true
                }
            }
        })
        if(arr.length === 0){
          var str = `
            <div>
              <h1>购物车空空如也<h1>
                <p>赶紧去列表页挑选喜欢的商品吧！</p>
                <p><a class="btn btn-primary btn-lg" href="list.html" role="button">go to list</a></p>
            </div>
          `
          $('.container').html(str)
        }
        //渲染数据 
        var str = ''
        data.forEach(item  => {
          //item中只有tradeItemId - 从arr中找到对应的number
          var number = arr.find(v=>v.id === item.tradeItemId).number
            str+=`
              <tr>
                <td><input type="checkbox" checked name="selectOne"></td>
                  <td><img src="${item.img}" width="100" height="100"></  td>
                  <td>${item.title}</td>
                  <td>${item.price}</td>
                  <td  data-id="${item.tradeItemId}">    
                      <button name="reduce">-</button>
                      <input type="number" value="${number}">
                      <button name="add"  data-number=${item.goods_number}>+</button>
                  </td>
                  <td>${(item.price * number).toFixed(2)}</td>
                  <td class="remove">删除<td>
              </tr>
            `
        });  
        $('.cart tbody').html(str) 
        //清空购物车
        clear()
        //删除
        remove()
        //计算总价和总数量
        count()
        //数量加减功能
        addReduce()
        //全选和单选
        selectAll()
      },
    }); 
    //清空购物车
    function clear(){
      document.querySelector('.clear').onclick = function(){
        layer.confirm('您确定要全部清空吗',{
          btn:['确定','取消']
        },()=>{
          layer.msg('清空购物车成功',{
              icon:1,
              time:1000
            })
          var str = `
            <div>
              <h1>购物车空空如也<h1>
                <p>赶紧去列表页挑选喜欢的商品吧！</p>
                <p><a class="btn btn-primary btn-lg" href="list.html" role="button">go to list</a></p>
            </div>
          `
          $('.container').html(str)
        localStorage.removeItem('data')
        })
      }
    }
    //删除购物车
    function remove(){
      var removes = document.querySelectorAll('.remove');
      for(var i=0;i<removes.length;i++){
        removes[i].onclick = function(){
          layer.confirm('您确定要删除该商品吗?',{
            btn:['确定','取消']    
          },()=>{
            layer.msg('删除成功',{
              icon:1,
              time:1000
            })
            // 删除tr
            this.parentElement.parentElement.removeChild(this.parentElement)
             //删除本地存储的数据
              // 获取本地存储数据
            var arr = localStorage.getItem('data')
            arr = JSON.parse(arr)
            console.log(arr);
            // console.log(arr);
              //从中筛选到当前这条数据下标
            var index = arr.findIndex(item=>item.id == this.previousElementSibling.previousElementSibling.getAttribute('data-id'))
            console.log(index);
            arr.splice(index,1)
            var data = arr.filter(item=>{   
            for(var i=0;i<arr.length;i++){
                if(arr[i].id === item.tradeItemId){
                    return true
                }
            }
        })
        if(arr.length === 0){
          var str = `
            <div>
              <h1>购物车空空如也<h1>
                <p>赶紧去列表页挑选喜欢的商品吧！</p>
                <p><a class="btn btn-primary btn-lg" href="list.html" role="button">go to list</a></p>
            </div>
          `
          $('.container').html(str)
        }
        //删除以后的数组重新存入本地存储
        localStorage.setItem('data',JSON.stringify(arr))
          })
        }
      }
    }
    //计算总价和总数量
    function count(){
        // 计算总数量 - 被选中的复选框对应的数量累加
        var selectOne = document.querySelectorAll('[name="selectOne"]')
        var totalNum = 0
        var totalPrice = 0
        for(var i=0;i<selectOne.length;i++){
          if(selectOne[i].checked){
            //将这个对应的数量获取到
            totalNum += selectOne[i].parentElement.parentElement.children[4].children[1].value - 0
  
            totalPrice += selectOne[i].parentElement.parentElement.children[5].innerText - 0
          }
        }
        document.querySelector('.totalNum').innerText = totalNum
        document.querySelector('.totalPrice').innerText = totalPrice.toFixed(2)
    }
    //数量加减功能
    function addReduce(){
      // 获取所有减按钮
      var reduceBtns = document.querySelectorAll('[name="reduce"]')
      for(var i=0;i<reduceBtns.length;i++){
        reduceBtns[i].onclick = function(){
          var number = this.nextElementSibling.value
          number = number - 1
          //限制最小值
          if(number<=1){
            number = 1
          }
          this.nextElementSibling.value = number  
          //还需要该改变本地存储中的number
          var arr = localStorage.getItem('data')
          arr = JSON.parse(arr)
          var obj = arr.find(item=>item.id == this.parentElement.getAttribute('data-id'))
          obj.number = number
          localStorage.setItem('data',JSON.stringify(arr))
  
          //修改小计
          this.parentElement.nextElementSibling.innerText = (number * this.parentElement.previousElementSibling.innerText).toFixed(2)
          count()
        }
      }
  
      //获取所有加按钮
      var addBtns = document.querySelectorAll('[name="add"]')
      for(var i=0;i<addBtns.length;i++){
        addBtns[i].onclick = function(){
          //获取数量
          var number = this.previousElementSibling.value;
          number = number-0 +1
          //限制最大值
          if(number>30){
            number = 30
          }
          //放到数量框中
          this.previousElementSibling.value = number
  
          
          //还需要改变本地存储中的number
          var arr = localStorage.getItem('data')
          arr = JSON.parse(arr)
          var obj = arr.find(item=>item.id === this.parentElement.getAttribute('data-id'))
          obj.number = number
          localStorage.setItem('data',JSON.stringify(arr))
  
          //修改小计
          this.parentElement.nextElementSibling.innerText = (number *  this.parentElement.previousElementSibling.innerText).toFixed(2)
          count()
        }
      }
    }
    //全选和单选
    function selectAll(){
      // 点击全选，都选中
      var selectAll = document.querySelectorAll('[name="selectAll"]')  
      var selectOne = document.querySelectorAll('[name="selectOne"]')
      console.log(selectAll,selectOne);
      for(var i=0;i<selectAll.length;i++){
        selectAll[i].onclick = function(){
          //其他所有的dan选根据点击的selectAll设置选中状态
              //遍历selectOne都设置
              for(var j=0;j<selectOne.length;j++){
                selectOne[j].checked = this.checked
              }
              for(var j=0;j<selectAll.length;j++){
                selectAll[j].checked = this.checked
              }
              count()
        }
      }
        //将selectOne转成数组
        var arr = [].slice.call(selectOne)
        arr.forEach(item=>{
          item.onclick = function(){
            //判断是否全部选中
            var bool = arr.every(v=>v.checked)
            //根据获取到bool设置两个全选
            for(var i=0;i<selectAll.length;i++){
              selectAll[i].checked = bool
            } 
            count()
          }
        })
  
    }